"use client";
import { Button } from "@nextui-org/button";
import { Skeleton } from "@nextui-org/skeleton";
import { Card, CardHeader } from "@nextui-org/card";
import { Input } from "@nextui-org/input";
import { Divider } from "@nextui-org/divider";
import { useState } from "react";

export default function Home() {
  const initPageData = () => {
    return {
      location: {
        city: "",
        name: "",
      },
      now: {
        text: "",
        temp: "",
        rh: "",
        wind_class: "",
        wind_dir: "",
      },
    }
  }
  let [pageData,setPageData] = useState(initPageData());
  const [tips, setTips] = useState("这里显示查询结果");

  const [city, setCity] = useState("");

  const [isLoaded, setIsLoaded] = useState(false);

  async function queryWeatherReport(city: string) {
    setIsLoaded(false);
    try {
      let weatherData = await fetch(`/api/get-weather-report?city=${city}`);
      if (!weatherData.ok) {
        // 如果响应状态码不是 2xx，抛出错误
        throw new Error(`HTTP error! status: ${weatherData.status}`);
      }

      const { data, code, msg } = await weatherData.json();
      if(code === 0) {
        setPageData(data);
      } else if (code === -1) {
        setPageData(initPageData());
        setTips(msg);
      }
    } catch (error) {
      setPageData(initPageData());
      setTips("查询失败");
    } finally {
      setTimeout(() => {
        setIsLoaded(true);
      }, 500);
    }
  }

  return (
    <div className="flex justify-between max-w-[480px] mx-auto flex-col gap-5">
      <Card className="py-4 bg-gradient-to-tr from-[#ececed] to-[#d6d6d7] dark:from-black dark:to-black dark:border dark:border-gray-50 dark:border-opacity-30">
        {!pageData.location.city ? (
        <CardHeader className="flex gap-4 items-center justify-center">
          <div className="h-14 flex items-center text-3xl opacity-20">{tips}</div>
        </CardHeader>
        ) : (
          <CardHeader className="flex gap-4">
            <Skeleton isLoaded={isLoaded} className="min-w-24 h-12 rounded-lg">
              <h2 className="text-5xl whitespace-nowrap">
                {pageData.location.name}
              </h2>
            </Skeleton>
            <div className="flex flex-col gap-1">
              <Skeleton isLoaded={isLoaded} className="max-w-16 h-8 rounded-lg">
                <p className="text-2xl">{pageData.now.temp}°C</p>
              </Skeleton>
              <Skeleton isLoaded={isLoaded} className="min-w-48 rounded-lg">
                <div className="flex items-center flex-wrap gap-1">
                  <span className="text-small text-default-500">
                    {pageData.now.wind_dir} {pageData.now.wind_class}
                  </span>
                  <Divider
                    className="mx-1 h-4 invisible sm:visible"
                    orientation="vertical"
                  />
                  <span className="text-small text-default-500">
                    相对湿度({pageData.now.rh}%)
                  </span>
                </div>
              </Skeleton>
            </div>
            <Skeleton isLoaded={isLoaded} className="w-7 h-7 rounded-lg ml-auto mr-4 self-start">
              <div className="text-xl ml-auto mr-4 self-start whitespace-nowrap">
                {pageData.now.text}
              </div>
            </Skeleton>
          </CardHeader>
        )}
      </Card>
      <Input
        label="输入城市查询天气"
        type="text"
        value={city}
        onValueChange={setCity}
      />
      <Button
        color="primary"
        size="lg"
        onClick={() => queryWeatherReport(city)}
      >
        查 询
      </Button>
    </div>
  );
}
